using UnityEngine;
using System.Collections;

public class MatchHelper : MonoBehaviour {
	/// <summary>
	/// Elevation from source to  angle.
	/// </summary>
	/// <returns>
	/// The angle.
	/// </returns>
	/// <param name='source'>
	/// Source.
	/// </param>
	/// <param name='target'>
	/// Target.
	/// </param>
    public static float ElevationAngle(Transform source, Transform target) {
	    // find the target vector:
	    Vector3 dir = target.position - source.position;
	    // create a horizontal version of it:
	    Vector3 dirH = new Vector3(dir.x, 0, dir.y);
	    // measure the unsigned angle between them:
	    float ang = Vector3.Angle(dir, dirH);
		
	    // add the signal (negative is below the source):
	    if (dir.y < 0) 
			ang = -ang;
	    return ang;
    }
 	/// <summary>
 	/// Elevations the angle clamped.
 	/// </summary>
 	/// <returns>
 	/// The angle clamped.
 	/// </returns>
 	/// <param name='source'>
 	/// Source.
 	/// </param>
 	/// <param name='target'>
 	/// Target.
 	/// </param>
 	/// <param name='minAng'>
 	/// Minimum angle.
 	/// </param>
 	/// <param name='maxAng'>
 	/// Max angle.
 	/// </param>
	public static float ElevationAngleClamped(Transform source,Transform target, float minAng = 15f, float maxAng=85f)
	{
		return Mathf.Clamp(ElevationAngle(source,target), 15, 85);
	}
	/// <summary>
	///  calculates the necessary velocity to reach a target given the launching angle,the source and the target 
	/// </summary>
	/// <returns>
	/// velocity
	/// </returns>
	/// <param name='source'>
	/// Source
	/// </param>
	/// <param name='target'>
	/// Target
	/// </param>
	/// <param name='angle'>
	/// Angle
	/// </param>
	/// 
	public static Vector3 BallisticVel(Transform source, Transform target,float angle) {
		Vector3 dir = target.position - source.position;  // get target direction
		float h = dir.y;  // get height difference
		dir.y = 0;  // retain only the horizontal direction
		float dist = dir.magnitude;  // get horizontal distance
		float a = angle * Mathf.Deg2Rad;  // convert angle to radians
		dir.y = dist * Mathf.Tan(a);  // set dir to the elevation angle
		dist += h / Mathf.Tan(a);  // correct for small height differences
		// calculate the velocity magnitude
		float vel = Mathf.Sqrt(dist * Physics.gravity.magnitude / Mathf.Sin(2 * a));
		return vel * dir.normalized;
	}
}
